import {Upload, Button, message} from 'antd';
import React, {useState} from 'react';
import {UploadOutlined} from '@ant-design/icons';
import axios from '../../http/axios';

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
export default class Demo extends React.Component {
  state = {
    fileList: [],
    uploading: false,
  };

  handleUpload = () => {
    const {fileList} = this.state;
    let file = fileList[0];
    console.log(fileList[0]);
    const formData = new FormData();
    fileList.forEach((file) => {
      formData.append('files[]', file);
    });
    this.setState({
      uploading: true,
    });
    console.log('fromData',formData);
    // You can use any AJAX library you like
    axios({
      url: '/upload/tengxunFood',
      method: 'POST',
      data: file,
    })
      .then((res) => {
        console.log(res)
        res.json()})
  };

  render() {
    const {uploading, fileList} = this.state;
    const props = {
      onRemove: (file) => {
        this.setState((state) => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: (file) => {
        console.log(file)
        this.setState((state) => ({
          fileList: [...state.fileList, file],
        }));
        return false;
      },
      handleChange : async (info) => {
        console.log(info.file.originFileObj);
        let fromData = await getBase64(info.file.originFileObj);
        console.log(fromData);
        axios({
          url: '/upload/tengxunFood',
          method: 'POST',
          data: {file: info.file},
        }).then((res) => {
          console.log(res);
          res.json();
        });
      },
      fileList,
    };

    return (
      <>
        <Upload {...props}>
          <Button icon={<UploadOutlined />}>Select File</Button>
        </Upload>
        <Button
          type="primary"
          onClick={this.handleUpload}
          disabled={fileList.length === 0}
          loading={uploading}
          style={{marginTop: 16}}
        >
          {uploading ? 'Uploading' : 'Start Upload'}
        </Button>
      </>
    );
  }
}
